package main

import (
	"fmt"
	"os"
	"os/signal"
	"path/filepath"
	"strings"
	"time"

	"gitee.com/zfd81/dbrs/log"

	"gitee.com/zfd81/dbrs/config"

	"gitee.com/zfd81/dbrs/server/cmd"

	"gitee.com/zfd81/dbrs/store"

	"github.com/sirupsen/logrus"
)

var (
	conf = config.GetConfig()
)

func init() {
	//初始化配置文件
	config.InitConfig()

	//设置日志打印格式
	logrus.SetFormatter(&logrus.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02 15:04:05", //时间格式
	})

	//设置日志级别
	level := logrus.InfoLevel
	switch strings.ToUpper(conf.Log.Level) {
	case "ERROR":
		level = logrus.ErrorLevel
	case "WARN":
		level = logrus.WarnLevel
	case "DEBUG":
		level = logrus.DebugLevel
	case "TRACE":
		level = logrus.TraceLevel
	}
	logrus.SetLevel(level)

	//日志文件设置
	hook, err := log.NewFileHook(filepath.Join(conf.Log.Path, "logs", fmt.Sprintf("dbrs_%d", conf.Port)))
	if err != nil {
		logrus.Fatalf("failed to log: %v", err)
	}
	logrus.AddHook(hook)
}

func exitHandle() {
	logrus.Infof("Databroker server is now ready to exit...\n")
	time.Sleep(1 * time.Second)
	os.Exit(1)
}

func main() {
	defer func() {
		if err := recover(); err != nil {
			logrus.Error(err)
		}
	}()

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)
	go func() {
		select {
		case <-c:
			exitHandle()
		}
	}()

	//初始化存储
	store.InitStorage()

	cmd.Execute()
}
